package com.ldk.admin.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.ldk.base.framework.util.SystemUtil;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import com.ldk.admin.common.LigerUIGridResult;
import com.ldk.admin.common.ResponseResult;
import com.ldk.admin.constants.FORM;
import com.ldk.admin.factory.MenuExt;
import com.ldk.admin.factory.MenuFactory;
import com.ldk.base.framework.common.CustomPageable;
import com.ldk.framework.entity.Menu;
import com.ldk.framework.entity.Role;
import com.ldk.framework.service.IMenuService;
import com.ldk.framework.service.IRoleService;

@Controller
@RequestMapping("/role")
public class RoleController extends BaseController {
	
	private String route = "role";
	private String module = "角色管理";
	
	
	@Autowired
	private IRoleService roleService;
	
	@Autowired
	private IMenuService menuService;
	
	@RequestMapping("/list")
	public ModelAndView list(ModelMap map, HttpServletRequest request,
							 HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		if (this.getRoleId(request) == 6) {
			setLinks(map, "", "", module, "/"+route+"/list", "", "");
		} else {
			setLinks(map, "", "", module, "/"+route+"/list", "添加"+module, "/"+route+"/add");
		}

		//操作日志
		//this.insertOplog(request,module,"","","查看",this.getAdminUserName(request).toString(), Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

		if (this.getRoleId(request) == 6) {
			return new ModelAndView("/role/listrole_sj");
		} else {
			return new ModelAndView("/role/listrole");
		}
	}
	
	@ResponseBody
	@RequestMapping("/getList")
	public LigerUIGridResult<Role> getList(@RequestParam(value="page",required=false,defaultValue="1") int page, 
			            @RequestParam(value="pagesize",required=false,defaultValue="10") int pageSize,
			            @RequestParam(value="roleName",required=false,defaultValue="") String roleName,
			            HttpServletRequest request)
	{
		int limit = pageSize;
		int offset = (page -1) * pageSize;
		
		Role query = new Role();
		if(!StringUtils.isEmpty(roleName)){
			query.setRoleName(roleName);
		}
		
		CustomPageable pageable = new CustomPageable(offset, limit);
		Page<Role> result = roleService.selectPageList("", query, pageable);
		
		LigerUIGridResult<Role> grid = new LigerUIGridResult<>();
		grid.Total = result.getTotalElements();
		grid.Rows = result.getContent();
		
		return grid;
	}
	
	@RequestMapping("/add")
	public ModelAndView add(ModelMap map, HttpServletRequest request,
							HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module, "/"+route+"/list", "添加"+module, "/"+route+"/add", "", "");
		setForm(map, "/"+route+"/insert", null);
		
		Role role = new Role();
		
		return new ModelAndView("/role/roleinfo","model", role);
	}
	
	@RequestMapping("/edit/{roleId}")
	public ModelAndView edit(@PathVariable int roleId, ModelMap map, HttpServletRequest request,
							 HttpServletResponse response)
	{
		//session是否过期
		this.isExpired(request,response);
		Role query = new Role();
		query.setRoleId(roleId);
		
		Role role = roleService.selectByKey("", query);
		if(role == null){
			return new ModelAndView("redirect:/"+route+"/list");
		}
		
		setLinks(map, module, "/"+route+"/list", "编辑"+module, "/"+route+"/edit/"+roleId, "", "");
		setForm(map, "/"+route+"/update", null);
		
		return new ModelAndView("/role/roleinfo","model", role);
	}
	
	@RequestMapping("/setMenu/{roleId}")
	public ModelAndView setMenu(@PathVariable int roleId, ModelMap map, HttpServletRequest request,
								HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		setLinks(map, module, "/"+route+"/list", module+"权限", "/"+route+"/setMenu/"+roleId, "", "");
		map.addAttribute("roleId", roleId);
		
		return new ModelAndView("/role/rolemenus");
	}
	
	@ResponseBody
	@RequestMapping("/getRoleMenus/{roleId}")
	public List<MenuExt> getRoleMenus(@PathVariable int roleId, ModelMap map)
	{
		List<Menu> menus = menuService.getRoleMenus("", roleId);
		
		MenuFactory factory = new MenuFactory();
		List<MenuExt> menuExts = factory.build(menus);
		
		return menuExts;
	}
	
	@ResponseBody
	@RequestMapping("/submitRoleMenus")
	//public ResponseResult submitRoleMenus(@RequestParam(value="roleId",required=false) int roleId,@RequestParam(value="menuIds[]",required=false) int[] menuIds)
	public ResponseResult submitRoleMenus(@RequestParam(value="roleId",required=false) int roleId,
										  @RequestParam(value="menuIds[]",required=false) int[] menuIds,HttpServletRequest request)
	{
		ResponseResult rst = new ResponseResult();
		
		Boolean succeed = false;
		try{
			succeed  = roleService.setRoleMenus("", roleId, menuIds);

			Role query = new Role();
			query.setRoleId(roleId);

			Role role = roleService.selectByKey("", query);

			//操作日志
			this.insertOplog(request,module,"","","设置角色:"+role.getRoleName()+"权限",this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
		}
		catch(Exception e){
			logger.error(e.getMessage());
		}
		
		if(succeed){
			rst.AddOk("设置角色权限成功");
		}
		else{
			rst.AddError("设置角色权限失败");
		}
		
		return rst;
	}
	
	@RequestMapping("/insert")
	public ModelAndView insert(@ModelAttribute("model") Role model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		
		try{
			
			if(model.getEnabled() == null){
				model.setEnabled(false);
			}

			//操作日志
			this.insertOplog(request,module,"","","添加角色:"+model.getRoleName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
			
		    int row = roleService.insert("", model);
		    if(row > 0){
		    	rst.AddOk("添加"+module+"成功");
		    }
		    else{
		    	rst.AddError("添加"+module+"失败");
		    }
		}
		catch(Exception e){
			rst.AddError("添加"+module+"失败");
		}
    	
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/role/add");
	}
	
	@RequestMapping("/update")
	public ModelAndView update(@ModelAttribute("model") Role model, RedirectAttributes redAttr, ModelMap map, HttpServletRequest request,
							   HttpServletResponse response){
		//session是否过期
		this.isExpired(request,response);
		ResponseResult rst = new ResponseResult();
		
		try{
			if(model.getEnabled() == null){
				model.setEnabled(false);
			}
			//操作日志
			this.insertOplog(request,module,"","","修改角色:"+model.getRoleName(),this.getAdminUserName(request).toString(),
					Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());

			int row = roleService.updateByKey("", model);
		    if(row > 0){
		    	rst.AddOk("修改"+module+"成功");
		    }
		    else{
		    	rst.AddError("修改"+module+"失败");
		    }
		}
		catch(Exception e){
			rst.AddError("修改"+module+"失败");
		}

		redAttr.addAttribute("roleId", model.getRoleId());
		redAttr.addFlashAttribute(FORM.FROM_RESULT, rst);
		
		return new ModelAndView("redirect:/role/edit/{roleId}");
	}
	
	@ResponseBody
	@RequestMapping("/remove/{roleId}")
	public ResponseResult remove(@PathVariable int roleId, HttpServletRequest request){
		
		ResponseResult rst = new ResponseResult();
		if(roleId < 1)
		{
			rst.AddError("删除"+module+"错误");
		}
		if(roleId == 1)
		{
			rst.AddError("不能删除超级管理员");
		}

		//操作日志
		Role query = new Role();
		query.setRoleId(roleId);
		Role role = roleService.selectByKey("", query);
		this.insertOplog(request,module,"","","删除角色:"+role.getRoleName(),this.getAdminUserName(request).toString(),
				Long.parseLong(this.getAdminId(request).toString()), SystemUtil.getAllSeconds());
		
		int row = roleService.deleteByKey("", query);
		if(row > 0){
			rst.AddOk("删除"+module+"成功");
		}
		else{
			rst.AddError("删除"+module+"失败");
		}
		
		return rst;
	}
}
